package com.mediacloud.app.newsmodule.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.appointment.AppointmentManager
import com.mediacloud.app.assembly.util.toast
import com.mediacloud.app.barrage.until.ScreenUtils
import com.mediacloud.app.model.NewsDateBean
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.utils.DateUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.video.live.CCTVNewsAdapter
import com.mediacloud.app.newsmodule.adaptor.video.vod.NewsDateAdapter
import com.mediacloud.app.newsmodule.fragment.simulcast.CCTVLiveStatus
import com.mediacloud.app.newsmodule.fragment.simulcast.SimulcastBean
import com.mediacloud.app.newsmodule.fragment.simulcast.SimulcastCalendarSheet
import com.mediacloud.app.newsmodule.fragment.simulcast.SimulcastV2Bean
import com.mediacloud.app.newsmodule.fragment.simulcast.TodayCCTVNews
import com.mediacloud.app.newsmodule.newsdetail_component.comment.CommentComponent
import com.mediacloud.app.newsmodule.utils.AppointmentController
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.yoake.media.player.XPlayer
import com.yoake.media.player.utils.XVideoBitRate
import com.yoake.media.player.utils.XVideoItem
import kotlinx.android.synthetic.main.activity_cctvnews_detail.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * 新闻联播详情页（可选日期）
 * */
class CCTVNewsDetailActivity : StyleSetActivity() {

    var year = 0
    var month = 0
    var day = 0
    var todayStamp: Long = 0L
    var targetIndex = 0
    var starTime = 0L
    var endTime = 0L
    var targetTime = 0L
    var sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)

    //获取最近一周的日期数据
    val dateList by lazy {
        DateUtils.getWeekList2()
    }

    val cctvNewsAdapter by lazy {
        CCTVNewsAdapter(R.layout.item_cctv_news)
    }

    var selectDatePos = 0 //被选中的日期位置

    var isTodayHaveNews = false

    var isPre = false //是否当日联播是预约状态

    val todayCatalogId by lazy {
        if (!TextUtils.isEmpty(intent.getStringExtra("todayCatalogId"))) intent.getStringExtra("todayCatalogId") else ""
    }

    //栏目id
    val catalogId by lazy {
        if (!TextUtils.isEmpty(intent.getStringExtra("catalogId"))) intent.getStringExtra("catalogId") else ""
    }

    //一级拆条id
    val firstCatalogId by lazy {
        if (!TextUtils.isEmpty(intent.getStringExtra("firstCatId"))) intent.getStringExtra("firstCatId") else ""
    }

    val dateAdapter by lazy {
        NewsDateAdapter(R.layout.item_cctv_news_date)
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_cctvnews_detail
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setDarkMode(this)

        setRecyclerView()

        otherSetting()

        initTimeDate()

        addClickListener()


        //获取今日直播状态
        getTodayNewsStatus(todayCatalogId)


    }

    private fun initTimeDate() {
        val targetData = Date(System.currentTimeMillis())
        val calendar = Calendar.getInstance()
        buildTime(targetData.time)
        calendar.time = targetData
        year = calendar.get(Calendar.YEAR)
        month = calendar.get(Calendar.MONTH) + 1
        day = calendar.get(Calendar.DAY_OF_MONTH)
    }

    private fun otherSetting() {
        //播放器顶部返回按钮设置，保证和UI的一致性
        val lp = player.titleView.layoutParams as MarginLayoutParams
        lp.topMargin = ScreenUtils.dpToPx(this, 50f).toInt()
        player.topView.visibility = View.GONE
        player.controller.getControllerInstance()?.setEnableOrientation(true)
        player.autoPlay = true
        player.isRelease = false
        player.prepareView.setVisibleThumb(true)
        player.completeView.setVisibleThumb(false)
        player.setPlayerType(XPlayer.VIDEO_VOD)
        player.titleView.hideTitleMoreView()

    }

    //设置几个列表
    private fun setRecyclerView() {
        //7日联播日期设置
        val linearSnapHelper = LinearSnapHelper()
        data_recycler_view.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        linearSnapHelper.attachToRecyclerView(data_recycler_view)
        dateAdapter.bindToRecyclerView(data_recycler_view)
        dateAdapter.setNewData(dateList)
        dateAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == selectDatePos) {
                //同一位置点击不做操作
                return@setOnItemClickListener
            }
            val item = adapter.getItem(position) as NewsDateBean
            changeSelectPos(position)
            if (position == 0) {
                if (isTodayHaveNews) {
                    getTodayDetail(todayCatalogId)
                } else {
                    setNoUI()
                    toast("今日无联播")
                }
            } else {
                getSelectDayData(item.searchTime, catalogId)
            }
        }

        //拆条数据列表
        recycler_items.layoutManager = LinearLayoutManager(this)
        cctvNewsAdapter.bindToRecyclerView(recycler_items)
        cctvNewsAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as SimulcastV2Bean
            val articleItem = ArticleItem()
            articleItem.id = item.id
            articleItem.type = 5
            articleItem.title = item.title
            NewsItemClickUtils.OpenItemNewsHandle(this, 5, articleItem, CatalogItem())
        }
    }

    /**
     * 改变被选中的日期的状态
     * 如果选中了最近7天以外的日期，position传-1即可
     * */
    fun changeSelectPos(position: Int) {
        selectDatePos = position
        for ((index, item) in dateList.withIndex()) {
            item.isChecked = index == position
        }
        dateAdapter.notifyDataSetChanged()
    }


    private fun addClickListener() {
        layout_choose_date.setOnClickListener {
            openDateSelector()
        }

    }

    fun openDateSelector() {
        var sheet = SimulcastCalendarSheet()
        val b = Bundle()
        b.putString("NID", catalogId)
        b.putInt("year", year)
        b.putInt("month", month)
        b.putInt("day", day)
        sheet!!.arguments = b
        sheet?.call = object : SimulcastCalendarSheet.SelectedCall {
            override fun onSelected(calendar: com.haibin.calendarview.Calendar?) {
                calendar?.let {
                    year = it.year
                    month = it.month
                    day = it.day
                    buildTime(it.timeInMillis)
                    dealSelectDate(sdf.format(Date(it.timeInMillis)))
                }
            }
        }
        sheet?.show(this.supportFragmentManager, "")
    }

    private fun buildTime(targetTime: Long) {
        this.targetTime = targetTime
        // 如果目标日期+15天大于了今天 开始时间就取 今天往前推31天
        if (targetTime + 15 * 3600 * 1000 * 24L > todayStamp) {
            starTime = todayStamp - 31 * 3600 * 1000 * 24L
            //结束时间一定要多出3天 否则不能居中
            val tempEndTime = targetTime + 3 * 3600 * 1000 * 24L
            if (tempEndTime > todayStamp) {
                endTime = tempEndTime

            } else {
                endTime = todayStamp
            }
        } else {
            //这种情况前后取15天
            starTime = targetTime - 15 * 3600 * 1000 * 24L
            endTime = targetTime + 15 * 3600 * 1000 * 24L
        }
        targetIndex = ((targetTime - starTime) / (3600 * 1000 * 24L)).toInt()
    }

    fun getTodayNewsStatusSuccess(status: CCTVLiveStatus?) {
        if (status == null) {
            toast("今日无直播")
            isTodayHaveNews = false
        } else {
            if (status.liveStatus == "0") {
                layout_subscribe.visibility = View.VISIBLE

                isPre = true
            }
            isTodayHaveNews = true
            getTodayDetail(todayCatalogId)
        }
    }

    /**
     * 设置当日新闻数据
     * */
    fun setTodayNews(todayCCTVNews: TodayCCTVNews?) {
        todayCCTVNews?.let {
            if (isDestroyed || isFinishing) return@let
            player.release()
            cctvNewsAdapter.setNewData(ArrayList())
            //播放器设置start
            player.setPoster(
                it.imagepath,
                null
            )

            if (!isPre) {
                val videoItem = XVideoItem(
                    it.title,
                    AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key,
                    AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                )
                val lineItem = XVideoBitRate()
                lineItem.path = it.livePath
                videoItem.bitRates.add(lineItem)
                player.addVideoItem(videoItem)
                player.start()
            } else {
                layout_subscribe.visibility = View.VISIBLE
                text_subscribe.text = it.startTime
                img_subscribe.isSelected = AppointmentManager.isAppointment("${it.articleId}", "0")
                val appointmentController =
                    AppointmentController(
                        this,
                        object : AppointmentController.AppointmentStatusListener {
                            override fun onAppointmentStatus(
                                contentId: String?,
                                appointmented: Boolean
                            ) {
                            }

                            override fun onAppointmentOk(
                                contentId: String?, appointmented: Boolean, count: Long
                            ) {
                                img_subscribe.isSelected =
                                    AppointmentManager.isAppointment("${it.articleId}", "0")
//                            img_subscribe.isSelected = appointmented
                            }

                            override fun onAppointmentErr(msg: String?) {

                            }

                        })
                img_subscribe.setOnClickListener {
                    appointmentController.Appointment(
                        "${todayCCTVNews.articleId}",
                        "${todayCCTVNews.title}",
                        15,
                        todayCCTVNews.startTime,
                        todayCCTVNews.endTime,
                        "0"
                    )
                }
            }
            //播放器设置end

            //基础UI设置
            text_news_title.text = it.title
            text_news_time.text = it.startTime

            val articleItem = ArticleItem()
            articleItem.id = it.articleId
            articleItem.type = 5
            articleItem.title = it.title
            articleItem.logo = it.imagepath
            articleItem.shareTitle = it.shareTitle
            articleItem.real_title = it.title
            articleItem.url = it.h5Url

            addComment(articleItem)

            refreshBottomStyle(articleItem, 1)
        }
    }

    /**
     * 设置选中日期的新闻数据
     * */
    fun setSelectDayNews(data: SimulcastBean?) {
        layout_subscribe.visibility = View.GONE
        if (data == null) {
            setNoUI()
            toast("当日无联播")
            return
        }


        data.let {
            //bugly异常 java.lang.IllegalArgumentException You cannot start a load for a destroyed activity
            if (isDestroyed || isFinish) return@let
            if (it.newsCastList.isEmpty())return@let
            val newCast = it.newsCastList[0]
            player.setPoster(newCast.logo, ContextCompat.getDrawable(this, R.drawable.cctv7_loading_img))
            val videoItem = XVideoItem(
                    newCast.title,
                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key,
                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
            )
            newCast.videoSimpleDtos.let { videos ->
                for (videoList in videos) {
                    if (videoList.type == "mp4Address") {
                        val formats = videoList.formats
                        for (format in formats) {
                            val lineItem = XVideoBitRate()
                            lineItem.path = format.url
                            lineItem.title = format.title
                            videoItem.bitRates.add(lineItem)
                        }
                    }
                }
            }
            if (videoItem.bitRates.isNotEmpty()) {
//                player.addVideoItem(videoItem, true)
                player.addVideoItemReverse(videoItem, "源码", true)
//                player.start()
            }

            cctvNewsAdapter.setNewData(it.firstSplitList)


            text_news_title.text = newCast.title
            text_news_time.text = newCast.publishDate

            val articleItem = ArticleItem()
            articleItem.id = newCast.id
            articleItem.type = 5
            articleItem.title = newCast.title
            addComment(articleItem)

            refreshBottomStyle(articleItem, 1)
        }

    }

    /**
     * 设置无直播时的UI
     * */
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun setNoUI() {
        text_news_title.text = ""
        text_news_time.text = ""
        cctvNewsAdapter.setNewData(ArrayList())
        comment_layout.removeAllViews()
        if (player.isPlaying) {
            player.pause()
        }
        player.release()
        player.setPoster("https://console.ahsx.ahtv.cn/b022db053480418d9c468bf07a330090.jpg",getDrawable(R.drawable.black_drawable))
    }

    /**
     * 添加评论数据，通过添加组件的方式添加
     * */
    private fun addComment(articleItem: ArticleItem) {
        val componentItem = ComponentItem()
        componentItem.page = 10
        comment_layout.removeAllViews()
        val hotComment = CommentComponent(this, supportFragmentManager, 1)
        hotComment.setCCTVDetailComponent(articleItem, componentItem, text_comment)
        comment_layout.addView(hotComment)
    }

    override fun getFitSystemWindow(): Boolean {
        return false
    }

    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun onDestroy() {
        super.onDestroy()
        player.release()
    }
}